<template>
  <div class="page-search">
    <hSearch v-bind="props.searchformConfig" v-model="formData" ref="formRef">
      <template #footer>
        <div class="search-btn">

          <el-button
            v-if="_options.showResetButton"
            type="default"
            :icon="RefreshLeft"
            @click="handleResetClick">重置</el-button>
          <el-button type="primary" 
          v-if="_options.showSearchButton"
          @click="handleQueryClick"><el-icon><ele-Search /></el-icon>查询</el-button>

          <el-button type="success" 
          v-if="_options.showAddButton"
          @click="handleAddClick"><el-icon><ele-CirclePlus /></el-icon>添加</el-button>

        </div>
      </template>
    </hSearch>
  </div>
</template>

<script setup lang="ts">
import hSearch from '/@/components/form/search.vue'
import { Options } from '/@/types/form/search'
import { Search, RefreshLeft } from '@element-plus/icons-vue'
import { ref, defineProps, defineExpose, defineEmits,ComputedRef ,computed} from 'vue'

const formRef = ref()
const emits = defineEmits(['handleQueryClick', 'handleResetClick','handleAddClick']);

interface Props {
  searchformConfig:Record<string, any>
  options?: Options
}

const props = defineProps<Props>();
// 设置option默认值，如果传入自定义的配置则合并option配置项
const _options: ComputedRef<Options> = computed(() => {
    const option = {
      showResetButton: false,  // 是否展示重置按钮
      showAddButton: true,    // 是否展示添加按钮
      showDeleteButton: false, // 是否展示删除按钮
      showSearchButton: true  // 是否展示搜索按钮
    }
    return Object.assign(option, props?.options)
})
const formItems = props.searchformConfig.formItems ?? [];
const formOriginData: any = {};
for (const item of formItems) {
  formOriginData[item.field] = '';
}
const formData = ref(formOriginData);
const handleResetClick = () => {
  // 直接赋值导致form 组件 formData=ref({...props.modelValue}) 浅拷贝 没有依赖
  // 解决办法一: 循环formData.value[`${key}`] = formOriginData[key];赋值form.value的属性,触发 hForm组件ref 更新

  // 解决办法二:不是用 使用formData=ref({...props.modelValue})  以及 不使用循环,以及hForm对值不使用双向绑定:从而使用:model-value="modleValue[`${item.field}`]" 和 @update:modelValue='handleValueChange($event,item.field)'
  // handleValueChange(value:any,field:string){ emists('upadate:modelValue',{...props.modelValue,[field]:value}) }
  //
  for (const key in formOriginData) {
    // 解决办法一
    formData.value[`${key}`] = formOriginData[key];
    // 解决办法二
    // formData.value = formOriginData;
  }
  emits('handleResetClick');
};
const handleQueryClick = () => {
  emits('handleQueryClick', formData.value);
};

const handleAddClick = () =>{
  emits('handleAddClick', formData.value);
}

// 暴露方法
defineExpose({
  formRef,
  formData,
  handleAddClick,
  handleQueryClick,
  handleResetClick
});
</script>

